package org.bizming.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.bizming.base.BaseErrCode;
import org.bizming.medicine.model.ShipmentMedicine;
import org.bizming.medicine.model.ext.ShipmentExt;
import org.bizming.medicine.service.ShipmentService;
import org.bizming.web.util.Helper;
import org.bizming.web.util.WebUtil;

public class ShipmentAction {

	private ShipmentService shipmentService;

	private ShipmentMedicine ext;

	public String addOrUpdate() {
		int errCode = BaseErrCode.SUCCESS;

		try {
			if (null != ext) {
				ext.setTime(System.currentTimeMillis() / 1000);
				shipmentService.add(ext);
			}

			WebUtil.getResponse().sendRedirect(
					WebUtil.getRequest().getContextPath() + "/shipment!selectList.action");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			errCode = BaseErrCode.SERVER_ERROR;
		}
		WebUtil.getRequest().setAttribute("code", errCode);
		WebUtil.getRequest().setAttribute("o", ext);
		return "addOrUpdate_exception";
	}

	/**
	 * 进入搜索页面
	 * 
	 * @return
	 */
	public String shipQueryPage() {
		return "shipQueryPage";
	}

	public String view() {
		ShipmentExt t = null;
		if (ext != null && ext.getId() != null) {
			t = shipmentService.get(ext.getId());
		}
		WebUtil.getRequest().setAttribute("o", t);
		return "view";
	}

	public String remove() throws IOException {
		try {
			if (ext != null && ext.getId() != null) {
				shipmentService.remove(ext.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		WebUtil.getResponse().sendRedirect(
				WebUtil.getRequest().getContextPath() + "/shipment!selectList.action");
		return null;
	}

	public String selectList() {
		List<ShipmentExt> list = shipmentService.selectList();
		if (!Helper.isEmpty(list)) {
			for (ShipmentExt t : list) {
				t.setTimeStr(convertTimeToStr(t.getTime()));
			}
		}
		WebUtil.getRequest().setAttribute("list", list);

		return "selectList";
	}

	private static String PATTERN = "yyyy-MM-dd";

	private String convertTimeToStr(long time) {
		SimpleDateFormat format = new SimpleDateFormat(PATTERN);
		Date date = new Date(time * 1000);
		return format.format(date);
	}

	// =======================================

	public ShipmentService getShipmentService() {
		return shipmentService;
	}

	public void setShipmentService(ShipmentService shipmentService) {
		this.shipmentService = shipmentService;
	}

	public ShipmentMedicine getExt() {
		return ext;
	}

	public void setExt(ShipmentMedicine ext) {
		this.ext = ext;
	}

}
